<template>
  <a-card class="general-card" title="满额活动" :bordered="false">
    <a-tabs @change="(val)=>{apiParams.promotionStatus = val}" :default-active-key="discountStatus">
      <a-tab-pane key="NEW" title="未开始"></a-tab-pane>
      <a-tab-pane key="START" title="已开始"></a-tab-pane>
      <a-tab-pane key="END" title="已结束"></a-tab-pane>
      <a-tab-pane key="CLOSE" title="已关闭"></a-tab-pane>
    </a-tabs>
    <searchTable
      :columns="columnsSearch"
      time-type="timestamp"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    />
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="add"> 添加 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getFullDiscountList"
      :api-params="apiParams"
      :bordered="true"
      @delete="remove"
    >
      <template #time="{ data }"
        >{{ data.startTime }}<span style="margin: 0 10px">-</span
        >{{ data.endTime }}</template
      >
      <template #view="{ data }">
        <a-button
          v-if="data.promotionStatus == 'NEW'"
          type="text"
          status="warning"
          @click="view(data)"
          >编辑</a-button
        >
        <a-button
          v-else
          type="text"
          status="success"
          @click="view(data, 'onlyView')"
          >查看</a-button
        >
      </template>
      <template #close="{ data }">
        <a-button
          v-if="data.promotionStatus === 'START'"
          type="text"
          status="danger"
          @click="openOrClose(data)"
          >关闭</a-button
        >
        <a-button
          v-if="data.promotionStatus === 'CLOSE'"
          type="text"
          status="success"
          @click="openOrClose(data)"
          >开启</a-button
        >
      </template>
    </tablePage>
  </a-card>
</template>

<script setup lang="ts">
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    getFullDiscountList,
    updateFullDiscount,
    delFullDiscount,
  } from '@/api/promotion';
  import {
    promotionStatus,
    promotionStatusSelect,
    fullMinusStatus,
  } from '@/utils/tools';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';

  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const router = useRouter();
  const tablePageRef = ref<any>();
  const discountStatus = ref<string>('START')
  const apiParams = ref<any>({sort: 'startTime',promotionStatus:discountStatus.value});


  const columnsSearch: Array<SearchRule> = [
    {
      label: '活动名称',
      model: 'promotionName',
      disabled: false,
      input: true,
    },
    {
      label: '活动状态',
      model: 'promotionStatus',
      disabled: false,
      select: {
        options: promotionStatusSelect,
      },
    },
    {
      label: '活动时间',
      model: 'selectDate',
      disabled: false,
      datePicker: {
        type: 'range'
      },
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '活动名称',
      dataIndex: 'promotionName',
      width: 250,
    },
    {
      title: '活动时间',
      dataIndex: 'time',
      width: 400,
      slot: true,
      slotTemplate: 'time',
    },

    {
      title: '活动类型',
      width: 200,
      dataIndex: 'fullMinusFlag',
      slot: true,
      slotData: {
        badge: fullMinusStatus,
      },
    },
    {
      title: '活动状态',
      dataIndex: 'promotionStatus',
      width: 200,
      slot: true,
      slotData: {
        badge: promotionStatus,
      },
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 240,
    methods: [
      {
        title: '查看',
        callback: 'view',
        slot: true,
        slotTemplate: 'view',
      },
      {
        title: '关闭',
        callback: 'close',
        slot: true,
        slotTemplate: 'close',
      },
      {
        title: '删除',
        callback: 'delete',
        type: 'text',
        status: 'danger',
      },
    ],
  };
  // 删除
  const remove = (val: any) => {
    modal.confirm({
      title: '确认删除',
      content: `确认删除此活动吗?`,
      alignCenter: false,
      onOk: async () => {
        delFullDiscount(val.record.id).then((res: any) => {
          if (res.data.success) {
            Message.success('删除成功');
            tablePageRef.value.init();
          }
        });
      },
    });
  };
  // 查看/编辑
  const view = (val: any, only?: any) => {
    let data: any;
    only ? (data = { onlyView: true, id: val.id }) : (data = { id: val.id });
    router.push({
      name: 'full-discount-detail',
      query: data,
    });
  };
  // 添加优惠券
  const add = (val: any) => {
    router.push({
      name: 'full-discount-detail',
    });
  };
  // 关闭
  const openOrClose = (row: any) => {
    let name = '开启';
    if (row.promotionStatus == 'START') {
      name = '关闭';
      modal.confirm({
        title: '提示',
        content: `确认${name}此活动吗?需要一定时间才能生效，请耐心等待`,
        alignCenter: false,
        onOk: async () => {
          const res = await updateFullDiscount(row.id);
          if (res.data.success) {
            Message.success(`${name}成功`);
            tablePageRef.value.init();
          }
        },
      });
    } else {
      const sTime = new Date();
      sTime.setMinutes(sTime.getMinutes() + 10);
      const eTime = new Date(
        new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1
      );
      const params = {
        startTime: sTime.getTime(),
        endTime: eTime.getTime(),
      };
      modal.confirm({
        title: '确认开启(默认为当前时间的十分钟之后)',
        content: `您确认要开启此拼团活动?`,
        alignCenter: false,
        onOk: async () => {
          const res = await updateFullDiscount(row.id, params);
          if (res.data.success) {
            Message.success(`开启活动成功`);
            tablePageRef.value.init();
          }
        },
        // render: (h:any) => {
        //      return h("div", [
        //        h("DatePicker", {
        //          props: {
        //            type: "datetimerange",
        //            placeholder: "请选择开始时间和结束时间",
        //            value: [sTime, eTime],
        //          },
        //          style: {
        //            width: "350px",
        //          },
        //          on: {
        //            input: (val:any) => {
        //              if (val[0]) {
        //                params.startTime = val[0].getTime();
        //              }
        //              if (val[1]) {
        //                params.endTime = val[1].getTime();
        //              }
        //            },
        //          },
        //        }),
        //      ]);
        //    },
      });
    }
  };
</script>
